package com.fjwt.gz.core.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/**
 * 微信消息通知加密工具类
 */
public class EncAesUtils {
    public EncAesUtils() {
    }

    public static String decode(String content, String key) throws Exception {
        System.out.println("content = " + content);
        byte[] arr = string2ByteArr(content);
        byte[] raw = key.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(2, skeySpec);
        byte[] original = cipher.doFinal(arr);
        return new String(original, "utf-8");
    }

    public static String encode(String content, String key) throws Exception {
        System.out.println("content = " + content);
        byte[] raw = key.getBytes("utf-8");
        SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(1, skeySpec);
        byte[] encrypted = cipher.doFinal(content.getBytes("utf-8"));
        return byteArrToString(encrypted);
    }

    public static String byteArrToString(byte[] buf) {
        StringBuffer sb = new StringBuffer();

        for(int i = 0; i < buf.length; ++i) {
            String hex = Integer.toHexString(buf[i] & 255);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    public static byte[] string2ByteArr(String str) {
        byte[] bytes = new byte[str.length() / 2];

        for(int i = 0; i < bytes.length; ++i) {
            bytes[i] = (byte)Integer.parseInt(str.substring(2 * i, 2 * i + 2), 16);
        }
        return bytes;
    }

    public static void main(String[] args) throws Exception {
        System.out.println(encode("1122", "sdsdsdsdsdsdsdsd"));
        System.out.println(decode("E54F56BB1F602E2536CD032B54AC7842", "sdsdsdsdsdsdsdsd"));
    }
}
